<template>
  <div class="l-tab-page" style="padding: 8px">
    <div class="l-auto-window h48" style="background-color: #fff">
      <el-tabs v-model="activeName">
        <el-tab-pane label="单位换算" name="first">
          <unitConversion :list="list" v-if="ready" />
        </el-tab-pane>
        <el-tab-pane label="单位换算配置" name="second">
          <unitConversionConfiguration
            v-if="ready"
            :loadData="loadData"
            :list="list"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
  
<script>
import unitConversion from "./unitConversion.vue";
import unitConversionConfiguration from "./config.vue";

const api = window.$api.erpcase.unitconvert;
const unittypeApi = window.$api.erpcase.unittype;
export default {
  components: {
    unitConversion,
    unitConversionConfiguration,
  },
  data() {
    return {
      activeName: "first",
      list: [],
      ready: false,
    };
  },
  mounted() {
    this.loadData();
  },
  methods: {
    async loadData() {
      this.ready = false;
      await this.lr_loadDataSourceData("ERP_Unit", false);
      const unitList = (this.lr_dataSourceData["ERP_Unit"] || []).filter(
        (t) => t.f_state == 0
      );

      const unitMap = {};
      unitList.forEach((item) => {
        unitMap[item.f_id] = item.f_name;
      });

      const typelist = await this.$awaitWraper(
        unittypeApi.getList({ f_State: 0 })
      );
      const converList = await this.$awaitWraper(api.getList());
      const converDetails = await this.$awaitWraper(api.getDetails());

      const list = [];
      const map = {};

      typelist.forEach((item) => {
        const row = {
          typeId: item.f_Id,
          typeName: item.f_Name,
          list:[]
        };
        row.units = unitList.filter((t) => t.f_unittypeid == item.f_Id);
        if (row.units.length > 0) {
          row.baseUnit = row.units.find((t) => t.f_isstandard == 0);
        }
        list.push(row);
        map[row.typeId] = row;
      });
      converList.forEach((item) => {
        const row = map[item.f_UnitTypeId];
        if (row) {
          row.converId = item.f_Id;
          row.list = converDetails.filter(
            (t) =>
              t.f_UnitConvertId == item.f_Id &&
              unitMap[t.f_UnitId] &&
              unitMap[t.f_ShiftUnitId]
          );
          const converDes = [];
          row.list.forEach((t) => {
            converDes.push(
              `1${unitMap[t.f_UnitId]}=${t.f_Quantity}${
                unitMap[t.f_ShiftUnitId]
              }`
            );
          });
          row.converDes = String(converDes);
        }
      });
      this.list = list;
      this.ready = true;
    },
  },
};
</script>